package com.hh.m15e.controller;

import cn.hutool.json.JSONUtil;
import com.hh.m15e.component.Param6201Util;
import com.hh.m15e.constant.HttpUrl;
import com.hh.m15e.domain.*;
import com.hh.m15e.domain.dto.ParamBody;
import com.hh.m15e.domain.dto.SignIn;
import com.hh.m15e.domain.po.DSbZydj;
import com.hh.m15e.domain.vo.InputParamVo;
import com.hh.m15e.domain.vo.OutputParamVo;
import com.hh.m15e.domain.vo.ResultVo;
import com.hh.m15e.service.IDSbZydjService;
import com.hh.m15e.service.ISPYHWX2SbJsService;
import com.hh.m15e.utils.CallsAPIUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

/**
 * 作者: Ⅹ玖
 * 创建日期：2025/2/24 10:02
 * 文档描述：院内费用明细上传接口
 */
@RestController
@RequestMapping("/api/details")
public class DetailsController {
    @Autowired
    private Param6201Util param6201Util;
    @Autowired
    private IDSbZydjService sbZydjService;
    @Autowired
    private ISPYHWX2SbJsService sPYHWX2SbJsService;

    @PostMapping("/upload")
    public OutputParamVo uploadDetails(@RequestBody ParamBody paramBody){
        CallsAPIUtil callsAPIUtil = new CallsAPIUtil();
        // 请求9001接口获取signNo
        String signNo = callsAPIUtil.callApi9001(new SignIn()).getSignNo();


        System.out.println("======================9001结果==========================");
        System.out.println(signNo);
        System.out.println("================================================");

        // 封装1101请求参数，并请求1101接口
        Input1101 input1101 = new Input1101(paramBody.getMdtrtCertType(),paramBody.getMdtrtCertNo());
        InputParamVo inputParam1101Vo = new InputParamVo("1101",signNo,input1101);
        OutputParamVo outputParam1101Vo = callsAPIUtil.callApi(HttpUrl.URL_1101, inputParam1101Vo);
        Output1101 output1101 = JSONUtil.toBean(outputParam1101Vo.getOutput(), Output1101.class);

        System.out.println("======================1101入参==========================");
        System.out.println(input1101);
        System.out.println("======================1101结果==========================");
        System.out.println(output1101);
        System.out.println("================================================");

        // 调用存储过程，获取数据库的参数
        Input6201 callProcess = param6201Util.getParam6201(paramBody.getTmh());

        System.out.println("======================存储过程入参==========================");
        System.out.println(paramBody.getTmh());
        System.out.println("========================存储过程========================");
        System.out.println(callProcess);
        System.out.println("================================================");

        //封装2201请求参数，并请求2201接口
        Input2201 input2201 = Input2201.builder()
                // 以下数据为接口1101获取
                .psnNo(output1101.getBaseinfo().getPsnNo())
                .insuType(output1101.getInsuinfo().getInsutype())
                .begntime(output1101.getIdetinfo().getBegntime())
                // 以下数据为接口请求参数获取
                .mdtrtCertType(paramBody.getMdtrtCertType())
                .mdtrtCertNo(paramBody.getMdtrtCertNo())
                // 以下数据为数据库获取
                .iptOtpNo(callProcess.getIptOtpNo())
                .deptCode(callProcess.getDeptCode())
                .deptName(callProcess.getDeptName())
                .caty(callProcess.getCaty())
                .build();
        InputParamVo inputParam2201Vo = new InputParamVo("2201",signNo, output1101.getInsuinfo().getInsuplcAdmdvs(),input2201);
        OutputParamVo outputParam2201Vo = callsAPIUtil.callApi(HttpUrl.URL_2201, inputParam2201Vo);
        Output2201 output2201 = JSONUtil.toBean(outputParam2201Vo.getOutput(), Output2201.class);

        System.out.println("======================2101入参==========================");
        System.out.println(input2201);
        System.out.println("========================2201结果========================");
        System.out.println(output2201);
        System.out.println("================================================");



        {
            //进行数据库数据留存
            DSbZydj dSbZydj = DSbZydj.builder()
                    .jylshOne(inputParam2201Vo.getMsgid())
                    .jylshTwo(callProcess.getMedOrgOrd())
                    .sblb("1028")
                    .fylb("3")
                    .tmh("ph")
//                .zyh(callProcess.getMedOrgOrd())
                    .brxm(output1101.getBaseinfo().getPsnName())
                    .brxb(output1101.getBaseinfo().getGend())
                    .brnl(output1101.getBaseinfo().getAge())
                    .sfzh(output1101.getBaseinfo().getCertno())
                    .zjlx(output1101.getBaseinfo().getPsnCertType())
                    .grbh(output1101.getBaseinfo().getPsnNo())
                    .xz(output1101.getInsuinfo().getInsutype())
                    /*   xz:1101.insuinfo[?].insutype
                       insutype为JSON数组,病人可能有多个待遇信息,进行2201登记也需要传入,这里建议获取方式为,
                       1101.insuinfo.psn_insu_stas人员参保状态为1的优先级大于其它所有,满足上述条件情况下,
                       310优先级大于390,待遇信息中多个待遇信息,只取310 340 390的数据。*/
                    .rylb(output1101.getInsuinfo().getPsnType())
                    .jbjg(output1101.getInsuinfo().getInsuplcAdmdvs())

                    .rybz("1")
                    .ryrq(LocalDateTime.now())
                    .ryjbrq(LocalDateTime.now())
                    .jzxh(output2201.getMdtrtId())
                    .dwbm(output1101.getIdetinfo().getPsnIdetType())

                    .dwmc(output1101.getInsuinfo().getEmpName()) //同上判断
                    .cbdtcqbm(output1101.getInsuinfo().getInsuplcAdmdvs())
                    .cbdfzxbm(output1101.getInsuinfo().getInsuplcAdmdvs())

                    .zylx("11")
                    .ksdm(input2201.getDeptCode())
                    .zgys(input2201.getAtddrNo())
                    .bz(output1101.getIdetinfo().getMemo()) //判断

                    .gwybz(output1101.getInsuinfo().getCvlservFlag())
                    .build();

            int maxAttempts = 3;
            boolean saved = false;
            for (int i = 0; i < maxAttempts && !saved; i++) {
                try {
                    int result = sbZydjService.saveData(dSbZydj);
                    if (result > 0) {
                        saved = true; // 保存成功，设置标志位
                        // 记录成功日志
                        System.out.println("数据保存成功");
                    } else {
                        // 记录失败日志
                        System.out.println("第 " + (i + 1) + " 次保存失败，尝试重新保存...");
                    }
                } catch (Exception e) {
                    // 记录异常日志
                    System.err.println("保存数据时发生异常: " + e.getMessage());
                    if (i == maxAttempts - 1) {
                        throw new RuntimeException("多次尝试保存数据失败", e);
                    }
                }
            }
        }


        //封装6201请求参数，并请求6201接口
        Input6201 input6201 =  callProcess.toBuilder()
                .psnNo(output1101.getBaseinfo().getPsnNo())
                .insutype(output1101.getInsuinfo().getInsutype())
                .begntime(output1101.getIdetinfo().getBegntime().toString())
//                .ecToken() //电子凭证解码返回
//                .deptName()//数据库查询
//                .caty()//数据库查询
                .mdtrtId(output2201.getMdtrtId())
//                .diseCodg()//病种编码
                .build();

        InputParamVo inputParam6201Vo = new InputParamVo("6201",signNo,  output1101.getInsuinfo().getInsuplcAdmdvs(),input6201);
        OutputParamVo outputParam6201Vo = callsAPIUtil.callApi(HttpUrl.URL_6201, inputParam6201Vo);
        Output6201 output6201 = JSONUtil.toBean(outputParam2201Vo.getOutput(), Output6201.class);


        System.out.println("======================6201入参==========================");
        System.out.println(input6201);
        System.out.println("=======================6201结果=========================");
        System.out.println(output6201);
        System.out.println("================================================");

        //封装6202请求参数，并请求6202接口
        Input6202 input6202 = Input6202.builder()
                .payAuthNo(paramBody.getPayAuthNo())
                .payOrdId(output6201.getPayOrdId())
                .payToken(output6201.getPayToken())
                .orgCodg(input6201.getOrgCodg())
                .orgBizSer(null) //业务流水号传null
                .chrgBchno(input6201.getChrgBchno())
                .feeType(input6201.getFeeType())
                .mdtrtId(output2201.getMdtrtId())
                .build();
        InputParamVo inputParam6202Vo = new InputParamVo("6202",signNo, output1101.getInsuinfo().getInsuplcAdmdvs(), input6202);
        OutputParamVo outputParam6202Vo = callsAPIUtil.callApi(HttpUrl.URL_6202, inputParam6202Vo);


        System.out.println("======================6202入参==========================");
        System.out.println(input6202);
        System.out.println("=======================6202结果=========================");
        System.out.println(JSONUtil.toBean(outputParam6202Vo.getOutput(), Output6202.class));
        System.out.println("================================================");


        return outputParam6202Vo;
    }

    @PostMapping("/add")
    public ResultVo saveDetail(@RequestBody InputParamVo inputParam){
        Input6302 input6302 = JSONUtil.toBean(inputParam.getInput(), Input6302.class);
        int count = sPYHWX2SbJsService.saveData(input6302);
        if(count > 0){
            return new ResultVo("0","接口调用成功",new Output6302(true,"院内处理回调成功"));

        }
        return new ResultVo("0","接口调用成功",new Output6302(false,"院内处理回调失败"));
    }

}
